package io.adminboot.service.impl;

import com.google.code.kaptcha.Producer;
import io.adminboot.entity.SysCaptcha;
import io.adminboot.entity.SysCaptchaExample;
import io.adminboot.exception.MyException;
import io.adminboot.repository.SysCaptchaMapper;
import io.adminboot.service.SysCaptchaService;
import io.adminboot.utils.DateUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.awt.image.BufferedImage;
import java.util.Date;
import java.util.List;

/**
 * 验证码
 */
@Service("sysCaptchaService")
public class SysCaptchaServiceImpl implements SysCaptchaService {
    @Autowired
    private Producer producer;
    @Autowired
    private SysCaptchaMapper mapper;

    @Override
    public BufferedImage getCaptcha(String uuid) {
        if (StringUtils.isBlank(uuid)) {
            throw new MyException("uuid不能为空");
        }
        //生成文字验证码
        String code = producer.createText();

        SysCaptcha captchaEntity = new SysCaptcha();
        captchaEntity.setUuid(uuid);
        captchaEntity.setCode(code);
        //5分钟后过期
        captchaEntity.setExpireTime(DateUtils.addDateMinutes(new Date(), 5));
        mapper.insert(captchaEntity);

        return producer.createImage(code);
    }

    @Override
    public boolean validate(String uuid, String code) {
        SysCaptcha captchaEntity = null;
        SysCaptchaExample example = new SysCaptchaExample();
        example.createCriteria().andUuidEqualTo(uuid);
        List<SysCaptcha> list = mapper.selectByExample(example);
        if (CollectionUtils.isEmpty(list)) {
            return false;
        }

        captchaEntity = list.get(0);
        //删除验证码
        mapper.deleteByPrimaryKey(uuid);

        if (captchaEntity.getCode().equalsIgnoreCase(code) && captchaEntity.getExpireTime().getTime() >= System.currentTimeMillis()) {
            return true;
        }

        return false;
    }
}
